package com.ympc.controller;

import com.ympc.pojo.Assignment;
import com.ympc.pojo.Class;
import com.ympc.pojo.StudentAssignment;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.AssignmentService;
import com.ympc.service.ClassService;
import com.ympc.service.StudentAssignmentService;
import com.ympc.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 班级管理控制器
 */
@Controller
@RequestMapping("/class")
public class ClassController {
    
    @Resource
    private ClassService classService;
    
    @Resource
    private TeacherService teacherService;
    
    @Resource
    private AssignmentService assignmentService;
    
    @Resource
    private StudentAssignmentService studentAssignmentService;
    
    /**
     * 班级列表页面（教师管理的班级）
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String classList(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        List<Class> classes;
        try {
            classes = classService.getClassesByTeacherId(teacher.getId());
        } catch (Exception e) {
            e.printStackTrace();
            classes = new java.util.ArrayList<>();
            model.addAttribute("error", "查询班级列表时出错：" + e.getMessage());
        }
        model.addAttribute("classes", classes);
        return "class/list";
    }
    
    /**
     * 添加班级页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addClassPage(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        return "class/add";
    }
    
    /**
     * 添加班级
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addClass(Class clazz, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        clazz.setTeacherId(teacher.getId());
        try {
            boolean success = classService.addClass(clazz);
            if (success) {
                model.addAttribute("message", "班级添加成功");
                return "redirect:/class/list";
            } else {
                model.addAttribute("error", "班级添加失败");
                return "class/add";
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "添加班级时出错：" + e.getMessage());
            return "class/add";
        }
    }
    
    /**
     * 编辑班级页面
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editClassPage(@RequestParam Integer id, Model model) {
        Class clazz = classService.getClassById(id);
        if (clazz == null) {
            model.addAttribute("error", "班级不存在");
            return "redirect:/class/list";
        }
        model.addAttribute("clazz", clazz);
        return "class/edit";
    }
    
    /**
     * 更新班级信息
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateClass(Class clazz, Model model) {
        boolean success = classService.updateClass(clazz);
        if (success) {
            model.addAttribute("message", "班级信息更新成功");
            return "redirect:/class/list";
        } else {
            model.addAttribute("error", "班级信息更新失败");
            model.addAttribute("clazz", clazz);
            return "class/edit";
        }
    }
    
    /**
     * 删除班级
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String deleteClass(@RequestParam Integer id, Model model) {
        boolean success = classService.deleteClass(id);
        if (success) {
            model.addAttribute("message", "班级删除成功");
        } else {
            model.addAttribute("error", "班级删除失败");
        }
        return "redirect:/class/list";
    }
    
    /**
     * 查看班级学生完成情况（选择作业）
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET)
    public String classStudentsPage(@RequestParam Integer id, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        Class clazz = classService.getClassById(id);
        if (clazz == null) {
            model.addAttribute("error", "班级不存在");
            return "redirect:/class/list";
        }
        
        // 获取该班级的所有作业
        try {
            List<com.ympc.pojo.Assignment> assignments = assignmentService.getAssignmentsByClassId(id);
            model.addAttribute("clazz", clazz);
            model.addAttribute("assignments", assignments);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取作业列表时出错：" + e.getMessage());
            model.addAttribute("assignments", new java.util.ArrayList<>());
        }
        
        return "class/students";
    }
    
    /**
     * 查看班级某个作业的学生完成情况
     */
    @RequestMapping(value = "/studentStatus", method = RequestMethod.GET)
    public String studentStatusPage(@RequestParam Integer classId,
                                     @RequestParam Integer assignmentId,
                                     HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        Class clazz = classService.getClassById(classId);
        if (clazz == null) {
            model.addAttribute("error", "班级不存在");
            return "redirect:/class/list";
        }
        
        Assignment assignment = assignmentService.getAssignmentById(assignmentId);
        if (assignment == null) {
            model.addAttribute("error", "作业不存在");
            return "redirect:/class/students?id=" + classId;
        }
        
        try {
            List<com.ympc.pojo.StudentCompletionStatus> statusList = 
                studentAssignmentService.getStudentCompletionStatus(assignmentId, clazz.getClassName());
            model.addAttribute("clazz", clazz);
            model.addAttribute("assignment", assignment);
            model.addAttribute("statusList", statusList);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取学生完成情况时出错：" + e.getMessage());
            model.addAttribute("statusList", new java.util.ArrayList<>());
        }
        
        return "class/studentStatus";
    }
}

